import './index.scss'
import {
  Card,
  Form,
  Button,
  Input,
  Space,
  Breadcrumb,
  Modal,
  Tag,
  message,
} from 'antd'
import { PlusOutlined } from '@ant-design/icons'
import 'react-quill/dist/quill.snow.css'
import './index.scss'
import { Link, useSearchParams } from 'react-router-dom'
import { useEffect,  useState } from 'react'
import CheckableTag from 'antd/es/tag/CheckableTag'
// 出场动画
import { TweenOneGroup } from 'rc-tween-one'
import labelList from '@/utils/lable'
import { useSelector } from 'react-redux'
import { getBlogAddAPI, getBlogInfoAPI, getBlogModifyAPI } from '@/api/blog'
import { getLabelAddAPI } from '@/api/label'
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { Editor, Toolbar } from '@wangeditor/editor-for-react'
import { getToken } from '@/utils/token'

// 工具栏配置
const toolbarConfig = { }                        

// 编辑器配置
const editorConfig = {                         
    placeholder: '请输入内容...',
    MENU_CONF:{ 
     uploadImage: {
     server: 'http://localhost:8080/upload',
     fieldName: 'image',
     // 自定义增加 http  header
     headers: {
         token: getToken()
     },
       customInsert(res, insertFn) {         
         if (res.code === 1)
           insertFn(res.data)
     },
}
}}
const Publish = () => {
  const [form] = Form.useForm()
   // editor 实例
   const [editor, setEditor] = useState(null)                 

   // 编辑器内容
   const [html, setHtml] = useState('') 

   // 及时销毁 editor ，重要！
   useEffect(() => {
       return () => {
           if (editor == null) return
           editor.destroy()
           setEditor(null)
       }
   }, [editor])

  //  博客标签
  const [isModalOpen, setIsModalOpen] = useState(false)
    const showModal = () => {
      setIsModalOpen(true)
    }
    const handleCancel = () => {
      setIsModalOpen(false)
    }
    const [selectedTags, setSelectedTags] = useState([])
    const handleChange = (tag, checked) => {
      const nextSelectedTags = checked
        ? [...selectedTags, tag]
        : selectedTags.filter((t) => t !== tag)
      setSelectedTags(nextSelectedTags)
    }

    const handleClose = (removedTag) => {
      const newTags = selectedTags.filter((tag) => tag !== removedTag)
      setSelectedTags(newTags)
    }
    
    const forMap = (tag) => {
      const tagElem = (
        <Tag
          closable
          onClose={(e) => {
            e.preventDefault()
            handleClose(tag)
          }}
        >
          {tag}
        </Tag>
      )
      return (
        <span
          key={tag}
        >
          {tagElem}
        </span>
      )
    }
    const tagChild = selectedTags.map(forMap)

    // 获取用户名
    const userInfo = useSelector(state => state.user.userInfo)
    const author = userInfo.username
    // 获取博客状态
    const [state, setState] = useState('')
    // 根据博客id判断是编辑博客还是发布博客
    const submitBlog = async (formValue) => {
      const cleanedText = html.replace(/<\/?p>/g, '')
      // 编辑博客
      if (articleId) {
        const res = await getBlogModifyAPI({id: articleId, title: formValue.title, text: cleanedText})
        if (res.code === 1) {
          message.success('修改成功')
          form.resetFields()
          // 遍历添加标签
          selectedTags.map(async (item) => {
            if (res.data)
              await getLabelAddAPI({ blogId: articleId,name: item})
          })
          setSelectedTags([])
          setHtml('')
        }
        else {
          message.error(res.msg)
        }
      } else {
        // 发布博客
        const res = await getBlogAddAPI({...formValue,userId: userInfo.id, state, author, text: cleanedText})
        if (res.code === 1 && state === "审核中") {
          message.success('文章已提交，等待管理员审核')
          form.resetFields()
          // 遍历添加标签
          selectedTags.map(async (item) => {
            if (res.data)
              await getLabelAddAPI({ blogId: res.data ,name: item})
          })
          setSelectedTags([])
          setHtml('')
        } else if (res.code === 1 && state === "草稿") {
          message.success('文章已存为草稿')
          form.resetFields()
          // 遍历添加标签
          selectedTags.map(async (item) => {
            if (res.data)
              await getLabelAddAPI({ blogId: res.data ,name: item})
          })
          setSelectedTags([])
          setHtml('')
        }
        else {
          message.error(res.msg)
        }
      }
    }

  // 博客编辑
  const [searchParams] = useSearchParams()
  const articleId = searchParams.get('id')
  useEffect(() => {
    async function getArticle () {
      const res = await getBlogInfoAPI(articleId)
      const { ...formValue } = res.data
      // 设置表单数据
      form.setFieldsValue({ ...formValue, text: setHtml(`<p>${res.data.text}</p>`)})
    }
    if (articleId) {
      // 拉取数据回显
      getArticle()
    }
  }, [articleId, form])
  return (
      <Card
      className='publish'
        title={
        <Breadcrumb items={[
          { title: <Link to={'/personal'}>首页</Link> },
          { title: `${articleId ? '编辑文章' : '发布文章'}` },
        ]}
        />
      }>
        <Form
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 16 }}
          initialValues={{ type: 1 }}
          form={form}
          onFinish={submitBlog}
        >
          <Form.Item
            label="标题"
            name="title"
          >
            <Input placeholder="请输入博客标题" style={{ width: 400 }} />
          </Form.Item>
          <Form.Item
            label="内容"
            name="text"
          >
            <div style={{ border: '1px solid #ccc', zIndex: 100}}>
                <Toolbar
                    editor={editor}
                    defaultConfig={toolbarConfig}
                    mode="default"
                    style={{ borderBottom: '1px solid #ccc' }}
                />
                <Editor
                    defaultConfig={editorConfig}
                    value={html}
                    onCreated={setEditor}
                    onChange={editor => setHtml(editor.getHtml())}
                    mode="default"
                    style={{ height: '500px', overflowY: 'hidden' }}
                />
            </div>
          </Form.Item>

          <Form.Item
            label="标签"
            name="title"
          >
            <div className="tag">
              <div
                style={{
                  marginBottom: 16,
                }}
              >
                <TweenOneGroup
                  enter={{
                    scale: 0.8,
                    opacity: 0,
                    type: 'from',
                    duration: 100,
                  }}
                  onEnd={(e) => {
                    if (e.type === 'appear' || e.type === 'enter') {
                      e.target.style = 'display: inline-block'
                    }
                  }}
                  leave={{
                    opacity: 0,
                    width: 0,
                    scale: 0,
                    duration: 200,
                  }}
                  appear={false}
                >
                  {tagChild}
                </TweenOneGroup>
              </div>
              <Button
                icon={<PlusOutlined />}
                onClick={showModal}>
                  添加博客标签
              </Button>
              <Modal 
                title="博客标签" 
                footer={[]}
                open={isModalOpen} 
                onCancel={handleCancel}>
                <Space size={[0, 8]} wrap>
                  {labelList.map((tag) => (
                    <CheckableTag
                      key={tag.id}
                      checked={selectedTags.includes(tag.name)}
                      onChange={(checked) => handleChange(tag.name, checked)}
                    >
                      {tag.name}
                    </CheckableTag>
                  ))}
                </Space>
              </Modal>
            </div>
          </Form.Item>
        <Form.Item name='state' wrapperCol={{ offset: 4 }}>
          <Space>
            <Button 
              size="large" 
              type="primary" 
              htmlType="submit" 
              icon={<PlusOutlined/>}
              onClick={() => setState("审核中")}>
              发布博客
            </Button>
            <Button   
              size="large" 
              type="primary" 
              htmlType="submit" 
              icon={<PlusOutlined/>}
              onClick={() => setState("草稿")}>
              存为草稿
            </Button>
          </Space>
        </Form.Item>
      </Form>
    </Card>
  )
}

export default Publish